/** 
 * @Title:  HomeController.java 
 * @author:  xuron
 * @data:  2015年11月23日 下午5:39:23 <创建时间>
 * 
 * @history：<以下是历史记录>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月23日 下午5:39:23 <修改时间>
 * @log: <修改内容>
 *
 * @modifier: <修改人>
 * @modify date: 2015年11月23日 下午5:39:23 <修改时间>
 * @log: <修改内容>
 */
package com.woyou.controller;

import java.util.ArrayList;
import java.util.List;

import com.jing.biandang.R;
import com.woyou.Constants;
import com.woyou.activity.HomeActivity;
import com.woyou.activity.LoginActivity;
import com.woyou.bean.FmInfo;
import com.woyou.bean.FragmentInfo;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.QueryNewOidListReq;
import com.woyou.bean.rpc.QueryNewOidListRes;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.SetShopStatusReq;
import com.woyou.component.ActionbarView;
import com.woyou.component.MenuView;
import com.woyou.component.SuperUI;
import com.woyou.fragment.MessageFragment;
import com.woyou.fragment.PWPanelFragment;
import com.woyou.fragment.order.CancelOrderFragment;
import com.woyou.fragment.order.NewOrderFragment;
import com.woyou.fragment.order.OrderFragment;
import com.woyou.fragment.shop.ShopFragment;
import com.woyou.model.GoodsManagerModel;
import com.woyou.model.OrderManageModel;
import com.woyou.model.rpc.OrderModel;
import com.woyou.model.rpc.ShopModel;
import com.woyou.service.MessageConnection;
import com.woyou.utils.LightManager;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.NavigationbarUtils;
import com.woyou.utils.PrintNumUtils;
import com.woyou.utils.SoundManager;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;
import com.woyou.utils.Utils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import net.simonvt.menudrawer.MenuDrawer;
import retrofit.RetrofitError;

/**
 * 抽取HomeActivity中的逻辑
 * 
 * @author xuron
 * @versionCode 1 <每次修改提交前+1>
 */
public class HomeController extends SuperController {

	private InputMethodManager imm;
	/**
	 * 主页面
	 */
	private HomeActivity homeActivity;
	private FragmentManager fm;
	private FragmentTransaction ft;
	private MenuDrawer menuDrawer;
	private ActionbarView actionbarView;
	/**
	 * OrderModel
	 */
	private OrderModel mOrderModel;
	/**
	 * 拼装新订单的列表
	 */
	public List<String> newOrderList = new ArrayList<String>();
	/**
	 * 拼装取消订单的列表
	 */
	public List<String> cancelOrderList = new ArrayList<String>();
	/**
	 * 定义一个是否能显示取消订单页面全局变量， 如果当前页面是新订单页面就不显示取消订单页面， 等新订单处理完后才进入取消订单
	 */
	public boolean isShowCancelOrder = true;
	/**
	 * 设置店铺营业状态
	 */
	private SetShopStatusReq setShopStatusReq = new SetShopStatusReq();
	private ShopModel mShopModel;
	
	/**
	 * 记录二级菜单要返回上一级的Fragment
	 */
	public Fragment backFragment;
	/**
	 * 记录当前显示的Fragment,以便当新订单来临的时候，被拒绝后 返回原有界面
	 */
	private Fragment currentFragment;

	private FragmentInfo fragmentInfo;
	/**
	 * 记录要返回的列表backFragments 记录要返回的对象fragmentInfo
	 */
	public List<FragmentInfo> backFragments = new ArrayList<FragmentInfo>();

	/**
	 * @param mContext
	 */
	public HomeController(Context mContext, FragmentManager fm, MenuDrawer menuDrawer, ActionbarView actionbarView) {
		super(mContext);
		this.mContext = mContext;
		this.fm = fm;
		this.menuDrawer = menuDrawer;
		this.actionbarView = actionbarView;
		homeActivity = (HomeActivity) mContext;
		mOrderModel = OrderModel.getInstance(mContext);
		mShopModel = ShopModel.getInstance(mContext);
		imm = (InputMethodManager) homeActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	/**
	 * 退出到登陆页面
	 */
	public void exitLogin() {
		// 清除登录信息
		aCache.clear();
		Utils.removeUserInfo2TF();
		LoginUtils.removeUserInfo(homeActivity);
		LoginUtils.removeUser(homeActivity);
		// 清除打印张数
		PrintNumUtils.clearPrintNum(homeActivity);
		runOnUI(new Runnable() {
			@Override
			public void run() {
				SuperUI.openToast(homeActivity, "您的账号已在其他地方登陆，请您重新登录!");
			}
		});
		OrderManageModel.getInstance().clearAllData();
		GoodsManagerModel.getInstance().clearAllData();
		// 关闭同步服务器时间
		if (actionbarView.refreshTimer != null) {
			actionbarView.refreshTimer.cancel();
			actionbarView.refreshTimer = null;
		}
		if (actionbarView.refreshTimerTask != null) {
			actionbarView.refreshTimerTask.cancel();
			actionbarView.refreshTimerTask = null;
		}
		// 关闭同步服务器时间的Timer
		if (actionbarView.serverTimer != null) {
			actionbarView.serverTimer.cancel();
			actionbarView.serverTimer = null;
		}
		if (actionbarView.serverTimerTask != null) {
			actionbarView.serverTimerTask.cancel();
			actionbarView.serverTimerTask = null;
		}
		// 设置营业状态
		actionbarView.isSettingShopStatus = false;
		NavigationbarUtils.getInstance(homeActivity).show();
		// 关闭闪烁灯
		LightManager.turnOnRedLight(false);
		LightManager.turnOnBlueLight(false);
		LightManager.turnOnRedBlueLight(false);
		// 关闭声音
		SoundManager.getInstance(homeActivity).stopSound();
		// 关闭心跳线程
		MessageConnection.getInstance().stopSocket();
		// 退出HomeActivity跳转到登陆页面
		Intent intent = new Intent(homeActivity, LoginActivity.class);
		homeActivity.startActivity(intent);
		homeActivity.finish();
	}

	/**
	 * 清除当前登录信息并跳转到登陆页面
	 */
	public void exit2Login() {
		// 设置店铺休息
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					setShopStatusReq.setStatus("C");
					final Result result = mShopModel.setShopStatus(setShopStatusReq);
					if (result != null && result.code == 1 || result != null && result.code == -3) {
						// 设置营业状态
						Constants.shopStatus = "C";
						// 清除登录信息
						aCache.clear();
						Utils.removeUserInfo2TF();
						LoginUtils.removeUserInfo(homeActivity);
						LoginUtils.removeUser(homeActivity);
						// 清除打印订单数
						PrintNumUtils.clearPrintNum(homeActivity);
						// 跳转到登陆页面
						Intent intent = new Intent(homeActivity, LoginActivity.class);
						homeActivity.startActivity(intent);
						homeActivity.finish();
					} else {
						runOnUI(new Runnable() {
							public void run() {
								SuperUI.openToast(homeActivity, result.msg);
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
					runOnUI(new Runnable() {
						public void run() {
							SuperUI.openToast(homeActivity, "请检查网络是否连接！");
						}
					});
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 验证老板密码 跳转到哪个fragment
	 */
	public void checkBossPW() {
		openFM(new FmInfo(PWPanelFragment.class, null,false));
	}

	/**
	 * 返回订单页面 type:true 跳转到未送订单页面 type:false 跳转到已送订单页面
	 */
	public void returnOrderFragment(boolean type,MenuView menuView) {
		try {
			menuView.menuViewController.showMark(menuView, 0);
			if (LoginUtils.getUserInfo(homeActivity) != null) {
				UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
				openFM(new FmInfo(OrderFragment.class, userInfo.getsName(),false));
			}
			if (type) {
				homeActivity.getOrderFm().layout_order_vp.setCurrentItem(0);
			} else {
				homeActivity.getOrderFm().layout_order_vp.setCurrentItem(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 清除Fragment碎片堆栈
	 */
	public void clearFragmentList() {
		List<Fragment> list = fm.getFragments();
		ft = fm.beginTransaction();
		// 遍历显示相应的Fragment
		for (Fragment fragment : list) {
			ft.remove(fragment);
		}
		ft.commitAllowingStateLoss();
		fm = null;
		ft = null;
	}

	/**
	 * 防止暴力点击
	 * 
	 * @return
	 */
	public void avoidForceClick(final View v) {
		v.setEnabled(false);
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				v.setEnabled(true);
			}
		}, 2000);
	}

	/**
	 * 处理取消订单
	 * 
	 * @param cancelOrder
	 */
	public void handleCancleOrder(String cancelOrder) {

		// 储存取消订单,拼装取消订单的列表数组
		if (cancelOrderList == null) {
			cancelOrderList = new ArrayList<String>();
		}
		cancelOrderList.add(cancelOrder);
		/**
		 * 根据isShowCancelOrder标志位判断能否显示CancelOrderFragment
		 */
		if (isShowCancelOrder) {
			jump2CancelOrder();
		}
	}

	/**
	 * 跳转到取消订单页面
	 */
	public void jump2CancelOrder() {
		try {
			hideInputMethod();
			openFM(new FmInfo(CancelOrderFragment.class, null,false));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 跳转到新订单页面
	 */
	public void jump2NewOrder() {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				try {
					// 隐藏键盘
					hideInputMethod();
					openFM(new FmInfo(NewOrderFragment.class, null,false));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 处理新订单
	 * 
	 * @param newOrder
	 */
	public void handleNewOrder(final ActionbarView actionbarView) {
		executeTask(new Runnable() {
			@Override
			public void run() {
				Result<List<QueryNewOidListRes>> newOrder = null;
				try {
					// 获取新订单列表
					for (int times = 1; times < 4; times++) {
						QueryNewOidListReq queryNewOidListReq = new QueryNewOidListReq();
						queryNewOidListReq.setsId(LoginUtils.getUserInfo(mContext).getsId());
						queryNewOidListReq.setPwd(LoginUtils.getUserInfo(mContext).getPwd());
						newOrder = mOrderModel.queryNewOidList(queryNewOidListReq);
						if (newOrder != null) {
							break;
						}
					}
					if (newOrder != null && newOrder.getCode() == 1 && newOrder.getData() != null
							&& newOrder.getData().size() > 0) {
						newOrderList.clear();
						List<QueryNewOidListRes> list = newOrder.getData();
						for (int i = 0; i < list.size(); i++) {
							newOrderList.add(list.get(i).getoId());
						}
						// 分发到handler中去处理
						jump2NewOrder();
					} else if (newOrder != null && newOrder.getCode() == -3) {
						exitLogin();
					}
				} catch (RetrofitError error) {
				}
			}
		});

	}
	
	/**
	 * 获取ShopFragment
	 * @return
	 */
	public ShopFragment getShopFm() {
		List<Fragment> fragments=fm.getFragments();
		for(Fragment fragment:fragments){
			if(fragment instanceof ShopFragment) {
				return (ShopFragment)fragment;
			}
		}
		return null;
	}
	/**
	 * 获取OrderFragment
	 * @return
	 */
	public OrderFragment getOrderFm() {
		List<Fragment> fragments=fm.getFragments();
		for(Fragment fragment:fragments){
			if(fragment instanceof OrderFragment) {
				return (OrderFragment)fragment;
			}
		}
		return null;
	}

	/**
	 * 获取NewOrderFragment
	 * @return
	 */
	public NewOrderFragment getNewOrderFm(){
		List<Fragment> fragments=fm.getFragments();
		for(Fragment fragment:fragments){
			if(fragment instanceof NewOrderFragment) {
				return (NewOrderFragment)fragment;
			}
		}
		return null;
	}

	/**
	 * 重置Actionbar
	 * 
	 * @param isClear
	 *            是否要清除backFragments列表
	 */
	public void resetActionBar(final boolean isClear) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				homeActivity.hideInputMethod();
				// 判断是否要清除backFragments列表
				if (isClear) {
					backFragments.clear();
				}
				if (backFragments.size() >= 2) {
					// 记录上一个Fragment和name以便操作返回按钮
					fragmentInfo = backFragments.get(0);
					backFragment = fragmentInfo.getBackFragment();
					actionbarView.layout_actionbar_back_tv.setText(fragmentInfo.getBackName());
					backFragments.remove(fragmentInfo);
					currentFragment = backFragment;
				} else if (backFragments.size() == 1) {
					// 记录上一个Fragment和name以便操作返回按钮
					fragmentInfo = backFragments.get(0);
					backFragment = fragmentInfo.getBackFragment();
					actionbarView.layout_actionbar_back_tv.setText(fragmentInfo.getBackName());
					backFragments.remove(fragmentInfo);
					currentFragment = backFragment;
				}
				if (backFragments.size() == 0) {
					actionbarView.layout_actionbar_switch.setVisibility(View.VISIBLE);
					actionbarView.layout_actionbar_back.setVisibility(View.GONE);
				} else {
					actionbarView.layout_actionbar_switch.setVisibility(View.GONE);
					actionbarView.layout_actionbar_back.setVisibility(View.VISIBLE);
				}
				// 如果当前fragment是OrderFragment则隐藏actionbar上的Home按钮,反之则反
				if (currentFragment instanceof OrderFragment) {
					if (LoginUtils.getUserInfo(homeActivity) != null) {
						UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
						actionbarView.layout_actionbar_shopname.setText(userInfo.getsName());
					}
					actionbarView.layout_actionbar_home.setVisibility(View.GONE);
				} else {
					actionbarView.layout_actionbar_home.setVisibility(View.VISIBLE);
				}
				// 如果当前fragment是MessageFragment则隐藏actionbar上的message按钮，反之则反
				if (currentFragment instanceof MessageFragment) {
					actionbarView.layout_actionbar_message.setVisibility(View.GONE);
				} else {
					actionbarView.layout_actionbar_message.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	/**
	 * 动态修改ActionBar
	 * 
	 * @param backFragment
	 * @param name
	 *            记录从哪个Fragment跳转过来的 和返回按钮的名字
	 */
	public void modifyActionBar(final Fragment fragment, final String name) {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				homeActivity.hideInputMethod();
				// 记录上一个Fragment和name以便操作返回按钮
				fragmentInfo = new FragmentInfo();
				fragmentInfo.setBackFragment(fragment);
				fragmentInfo.setBackName(name);
				backFragments.add(fragmentInfo);
				//
				backFragment = fragment;
				if (backFragments.size() == 0) {
					actionbarView.layout_actionbar_switch.setVisibility(View.VISIBLE);
					actionbarView.layout_actionbar_back.setVisibility(View.GONE);
				} else {
					actionbarView.layout_actionbar_switch.setVisibility(View.GONE);
					actionbarView.layout_actionbar_back.setVisibility(View.VISIBLE);
				}
				if (!TypeJudgeTools.isNull(name)) {
					actionbarView.layout_actionbar_back_tv.setText("" + name);
				}
				// 如果当前fragment是OrderFragment则隐藏actionbar上的Home按钮,反之则反
				if (currentFragment instanceof OrderFragment) {
					if (LoginUtils.getUserInfo(homeActivity) != null) {
						UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
						actionbarView.layout_actionbar_shopname.setText(userInfo.getsName());
					}
					actionbarView.layout_actionbar_home.setVisibility(View.GONE);
				} else {
					actionbarView.layout_actionbar_home.setVisibility(View.VISIBLE);
				}
				// 如果当前fragment是MessageFragment则隐藏actionbar上的message按钮，反之则反
				if (currentFragment instanceof MessageFragment) {
					actionbarView.layout_actionbar_message.setVisibility(View.GONE);
				} else {
					actionbarView.layout_actionbar_message.setVisibility(View.VISIBLE);
				}
			}
		});
	}
	/**
	 * 记录当前显示的Fragment,以便当新订单来临的时候，被拒绝后 返回原有界面
	 * @param currentFragment
	 */
	public void setCurrentFragment(Fragment currentFragment) {
		this.currentFragment = currentFragment;
	}
	/**
	 * 获取当前currentFragment
	 * @return
	 */
	public Fragment getCurrentFragment() {
		return currentFragment;
	}

	/**
	 * 返回上一个FM
	 */
	public void backBeforeFM() {
		ft = fm.beginTransaction();
		ft.setCustomAnimations(R.anim.activity_none, R.anim.activity_to_right);
		// 显示相应的Fragment
		for (Fragment fragment : fm.getFragments()) {
			if (fragment == backFragment) {
				ft.show(fragment);
			} else {
				ft.hide(fragment);
			}
		}
		ft.commitAllowingStateLoss();
		// 记录当前是哪个碎片
		currentFragment = backFragment;
		// 重置actionbar
		resetActionBar(false);
	}

 	/**
	 * 打开二级Fragment
	 */
	public void openSubFM(Fragment currentFm,FmInfo fmInfo) {
		String subTitle=fmInfo.getTitleName();
		Class<Fragment> nowClass=fmInfo.getClazzFM();
		String fmName = nowClass.getName();
		List<Fragment> list = fm.getFragments();
		Fragment nowFm = fm.findFragmentByTag("" + fmName);
		ft = fm.beginTransaction();
		if(fmInfo.isAnim()){
			ft.setCustomAnimations(R.anim.activity_to_left,R.anim.activity_none);
		}
		if (nowFm == null) {
			try {
				// 反射得到Fragment实例
				nowFm =nowClass.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			ft.add(R.id.layout_home_linear, nowFm,fmName);
		}
		// 遍历显示相应的Fragment
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				Fragment fragment = list.get(i);
				if (fragment.equals(nowFm)) {
					ft.show(fragment);
				} else {
					ft.hide(fragment);
				}
			}
		}else{
			ft.show(nowFm);
		}
		// 提交事务
		ft.commitAllowingStateLoss();
		if (menuDrawer.isMenuVisible()) {
			menuDrawer.toggleMenu();
		}
		/**
		 * 过滤掉订单和取消订单
		 */
		if(!(nowFm instanceof NewOrderFragment)&&!(nowFm instanceof CancelOrderFragment)){
			// 记录当前是哪个碎片
			currentFragment = nowFm;
		}
		modifyActionBar(currentFm,subTitle);
	}
 	/**
	 * 打开一个Fragment
	 */
	public void openFM(FmInfo fmInfo) {
		String titleName=fmInfo.getTitleName();
		Class<Fragment> nowClass=fmInfo.getClazzFM();
		String fmName = nowClass.getName();
		List<Fragment> list = fm.getFragments();
		Fragment nowFm = fm.findFragmentByTag("" + fmName);
		ft = fm.beginTransaction();
		if(fmInfo.isAnim()){
			ft.setCustomAnimations(R.anim.my_alpha_action, R.anim.activity_none);
		}
		if (nowFm == null) {
			try {
				// 反射得到Fragment实例
				nowFm =nowClass.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			ft.add(R.id.layout_home_linear, nowFm,fmName);
		}
		// 遍历显示相应的Fragment
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				Fragment fragment = list.get(i);
				if (fragment.equals(nowFm)) {
					ft.show(fragment);
				} else {
					ft.hide(fragment);
				}
			}
		}else{
			ft.show(nowFm);
		}

		// 提交事务
		ft.commitAllowingStateLoss();
		if (menuDrawer.isMenuVisible()) {
			menuDrawer.toggleMenu();
		}
		if(titleName!=null&&!titleName.equals("")){
			actionbarView.layout_actionbar_shopname.setText(titleName);
		}
		/**
		 * 过滤掉订单和取消订单
		 */
		if(!(nowFm instanceof NewOrderFragment)&&!(nowFm instanceof CancelOrderFragment)){
			// 记录当前是哪个碎片
			currentFragment = nowFm;
		}
		// 重置actionbar
		resetActionBar(true);
	}

	/**
	 * 隐藏输入法
	 */
	public void hideInputMethod() {
		if (homeActivity.getCurrentFocus() == null) {
			return;
		}
		imm.hideSoftInputFromWindow(homeActivity.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}
}
